#!/usr/bin/env python
# -*- coding: utf-8 -*-

from utils.util import datetime_now_str
from controls.mongo import db_shitouren as db
from pymongo import DESCENDING

# collection in mongodb
coll = db.city_product
"""db.city_product collection has
   cityid:          城市id(int)
   "products" : [
      {  "descs" : [
            {"content" : "美味等级","descid" : 1},
            {"content" : "送礼等级","descid" : 2},
            {"content" : "性价比","descid" : 3}
         ],
         "level" : 4.5,
         "name" : "地图",
         "pid" : 1,
         "taobaourl" : ""
      }
   ]
   ctime:           更新时间(str)
"""


def get_city_product(cityid):
    '''get city's products by cityid
    '''
    cond = {}
    if cityid:
        cond['cityid'] = int(cityid)
    else:
        return None
    res = coll.find_one(cond, {'_id': 0, 'cityid': 1, 'products': 1})

    return res


def is_exist(cityid):
    cond = {}
    if cityid:
        cond['cityid'] = int(cityid)
    else:
        return False
    res = coll.find(cond, {'_id': 1}).count()

    return res > 0


def add_city_product(cityid, products_list):
    '''add product for a city
    '''
    res = coll.insert({'cityid': int(cityid), 'products': products_list, 'ctime': datetime_now_str()})

    return res


def update_city_product(cityid, products_list):
    '''update product for a city
    '''
    res = None
    if is_exist(cityid):
        res = coll.update({'cityid': int(cityid)},
                          {'cityid': int(cityid), 'products': products_list, 'ctime': datetime_now_str()})
    else:
        res = add_city_product(cityid, products_list)

    return res


def del_city_product(cityid):
    '''del a comment by _id
    res:{u'syncMillis': 0, u'ok': 1.0, u'err': None, u'writtenTo': None, u'connectionId': 29, u'n': 1}
    '''
    res = coll.remove({'cityid': int(cityid)})
    return res


if __name__ == "__main__":
    print 'main start'
    print '=============insert test data'
    print update_city_product(999, [991, 992, 993])
    print add_city_product(998, [981, 982, 983])

    print '============='
    print get_city_product(999)
    print update_city_product(999, [994, 995, 996])
    print get_city_product(999)

    print '============='
    print is_exist(999)
    print is_exist(998)
    print del_city_product(999)
    print del_city_product(998)
    print is_exist(999)
    print is_exist(998)
